package Demo84;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 岛屿的数量
 * https://leetcode.cn/problems/number-of-islands/
 */
class Solution {
    boolean[][] vis;
    int n,m;
    int[] dx = new int[] {0,0,1,-1};
    int[] dy = new int[] {1,-1,0,0};

    public int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        vis = new boolean[m][n];
        int ret = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1' && vis[i][j] == false) {
                    // 遍历
                    floodFill(grid,i,j);
                    ret++;
                }
            }
        }
        return ret;
    }
    private void floodFill(char[][] grid, int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[] {i,j});
        vis[i][j] = true;
        while(!queue.isEmpty()) {
            int[] t = queue.poll();
            int a = t[0], b = t[1];

            for(int p = 0; p < 4; p++) {
                int x = a + dx[p], y = b + dy[p];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && vis[x][y] == false) {
                    queue.add(new int[] {x,y});
                    vis[x][y] = true;
                }
            }
        }
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int ret = solution.numIslands(new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}});
        System.out.println(ret);
    }
}